import {Api_url} from '../../config.js' 
import http from '../../axios.js'
import Vue from 'vue'

const Wxcode_url= Api_url+"/font/getCode"
const Token_url= Api_url+"/font/getOpenid"
const VerifyUrl = Api_url + 'auth/token_verify';

// 获取openid需到公众号平台设置：IP白名单 和 授权域名；
// ip是服务器IP，域名是前端域名

class WxToken { 	
	constructor() { 
	}	
	//初始化登陆
	async verify(e) { 		
		// 判断是否是微信浏览器打开
		var ua = navigator.userAgent.toLowerCase();
		var isWeixin = ua.indexOf('micromessenger') != -1;
		if (!isWeixin) { 
			console.log("非公众号-暂不登陆")
		    return false;
		} 
		var openid = uni.getStorageSync('token_openid'); //获取缓存
		if(!openid){
			this.login()	//获取openid
		}
	}	
	
	login(){		
		const code = this.GetUrlParame('code') // 截取code	
		if (!code) {
			this.get_code()
		}else{
			this.get_openid()
		}	
	}	
	get_code(){		 
		var domine = window.location.href; // 微信会自动识别#并且清除#后面的内容

		domine = domine.split("?code")[0]; 

		uni.request({
		  	url: Wxcode_url,
		  	method: 'GET', 
			data:{
				redirectUrl:domine
			},
		  	success: function (res) {   
				if(res.data.code == 200){
					window.location.href =res.data.data
				}
		  	}
		}); 
	}
	get_openid(e){
		//用code换取openid
		const code = this.GetUrlParame('code') // 截取code	
		const domine = window.location.href.split("?");
		let finallyUrl = "";
		const tail = domine[1].split("#")[1]
		if(domine.length == 3){
			finallyUrl = domine[0]+'#'+tail+"?"+domine[2]
		}else{
			finallyUrl = domine[0]+'#'+tail
		}
		
		console.log(finallyUrl)
		uni.request({
		  	url: Token_url,
		  	method: 'GET',
			data:{code},
		  	success: function (res) {
		  		if (res.data.data) { 
		  			uni.setStorageSync("token_openid", res.data.data);		
					
		  			window.location.href = finallyUrl 		 
		  		}
		  	}
		});  	
	}	
	
	//验证token
	_veirfyFromServer(token) {
		var that = this;
		uni.request({
			url: VerifyUrl,
			method: 'POST',
			data: {
				token: token
			},
			success: function(res) {
				var valid = res.data.isValid;
				if (!valid) {
					that.getOpenid()();
				}else{
					console.log("token有效")
				}
			}
		})
	}
	//截取code
	GetUrlParame(parameName) {  
		/// 获取地址栏指定参数的值
		/// <param name="parameName">参数名</param>
		// 获取url中跟在问号后面的部分
		var parames = window.location.search
		// 检测参数是否存在
		if (parames.indexOf(parameName) > -1) {
			var parameValue = ''
			parameValue = parames.substring(parames.indexOf(parameName), parames.length)
			// 检测后面是否还有参数
			if (parameValue.indexOf('&') > -1) {
				// 去除后面多余的参数, 得到最终 parameName=parameValue 形式的值
				parameValue = parameValue.substring(0, parameValue.indexOf('&'))
				// 去掉参数名, 得到最终纯值字符串
				parameValue = parameValue.replace(parameName + '=', '')
				return parameValue
			}
			return ''
		}
	}

} 

export { WxToken };